$(function(){		
	frame.init();
});

var debug = false;
var oc = "grapp";//only code
var url = "http://www.qianfuzhang.com/chrome";
var _loginCookie;
var _otherCookie;
if(debug){
	var host 	   = "http://www.grapp-web.com/index/";
	var adminhost  = "http://eqfast-grapp.grapp-web.com/"; 
}else{
	var host 	   = "http://grapp.qianfuzhang.com/index/";
	var adminhost  = "http://eqfast-grapp.qianfuzhang.com/";
}

function delCookie(name) {
  chrome.cookies.remove({"name": name,"url":url});
}
function setCookie(name,value) {
  chrome.cookies.set({"name": name,"value":value,"url":url},function(cookie){
	  _loginCookie = cookie.value;
	  $.cookie(oc,_loginCookie);
  });
}
function getCookie(name) {
  chrome.cookies.get({"name": name,"url":url},function(cookie){
	  _loginCookie = cookie.value;
	  $.cookie(oc,_loginCookie);
  });	
  return $.cookie(oc);
}

var frame = {
	init:function(data){
		this.body = "#mbody";
		if(data == undefined){
			_loginCookie = getCookie(oc);		   
			if(_loginCookie!= undefined){
				this.getHtml("working.html");
			}else{
				this.getHtml("login.html");
			}
		}else{
			this.getHtml(data);	
		}
	},
	getHtml:function(file){
		var _this = this;
		$.ajax({ 
			url: file, 
			success: function(data){
				$(_this.body).html(data);
				_this.listen(file);
				working.init(file);
			}
		});
	},
	listen:function(file){
		var _this = this;
		$.get(chrome.extension.getURL('manifest.json'), function(info){
			$("#version").html("v"+info.version);
		}, 'json');
		if(file=="login.html"){
			$("#login-submit").click(function(){
				if($("#username").val()==""){
					_this.showerror("账户不能为空");
					$("#username").focus();
				}else if($("#password").val()==""){
					_this.showerror("密码不能为空");
					$("#password").focus();
				}else{
					var username = $("#username").val();
					var password = $("#password").val();
					var xhr = new XMLHttpRequest();
					xhr.open("GET", host+'login/?username='+username+"&password="+password, true);
					xhr.onreadystatechange = function() {
						if (xhr.readyState == 4) {	
							var json = $.parseJSON(xhr.responseText);
							try { 
								if( json['status'] == 1){
									setCookie(oc,json['uid']);
									chrome.cookies.set({"name": oc+'_setting',"value":json['isshowadmin'],"url":url},function(cookie){
							_otherCookie = cookie.value;
	  						$.cookie(oc+'_setting',_otherCookie);				
						});
									_this.getHtml("working.html");
								}else{
									_this.showerror("账户或密码错误");	
								}
							}catch(e) {
								_this.showerror("通信失败");	
							}
						}
					}
					xhr.send();
				}
			});
		}else if(file=="working.html"){
			$("#logout").click(function(){
				_this.getHtml("login.html");	
				$.cookie(oc, null);
				delCookie(oc);
			});
		}
	},
	showerror:function(val){
		$(".error-msg-txt").html(val);
		$(".error-msg").show();	
	},
	closeerror:function(){
		$(".error-msg").hide();	
	}
}

var working = {
	init:function(file){
		this.host = host;
		this.do(file);
	},
	do:function(file){
		if(file=="login.html"){

		}else if(file=="working.html"){
			var xhr = new XMLHttpRequest();
			var uid = $.cookie(oc);
			var isshowadmin;
			chrome.cookies.get({"name": oc+'_setting',"url":url},function(cookie){
				isshowadmin = cookie.value;	
			});
			xhr.open("GET", this.host+'getlist/?uid='+uid, true);
			xhr.onreadystatechange = function() {
			  if (xhr.readyState == 4) {
				// 警告！可能会执行恶意脚本！
				//var resp = eval("(" + xhr.responseText + ")");
				var _json = $.parseJSON(xhr.responseText);
				$("#tbody").html("");
				var html  = "";
				if(_json == ""){
					$("#loading").html("没有数据");	
					return;
				}
				for(v in _json){
						html += '<tr>';
						html += '<td align="left">'+_json[v]['username']+'</td>';
						html += '<td align="right">';
						html += '<button type="button" class="login-btn am-btn am-btn-success am-btn-xs" data1="'+_json[v]['username']+'" data2="'+_json[v]['password']+'" account="'+_json[v]['id']+'">登陆</button>';
						html += '<button type="button" class="logout-btn am-btn am-btn-default am-btn-xs">退出</button>';							                    html += '</td>';
						html += '</tr>';
				}
				$("#tbody").html(html);
				$(".login-btn").click(function(){
					
					chrome.cookies.set({"name": oc+'_account',"value":$(this).attr('account'),"url":url},function(cookie){
	  						$.cookie(oc+'_account',cookie.value);				
					});
					
					var _this = this;
					chrome.tabs.create({
							'url': 'https://login.taobao.com/member/logout.jhtml?redirectURL=http%3A%2F%2Fwe.taobao.com%2F','selected':true
						},function(tab2) {

						}
					);
					var data1 = $(_this).attr("data1");
					var data2 = $(_this).attr("data2");
					chrome.runtime.sendMessage({'cmd':"mycmd","data1":data1,"data2":data2},function(response){console.log(response);});
				});
				
				if(isshowadmin==1 && isshowadmin!=null){
					
					$('#fastlogindiv').show();
					
					/* 登陆后台 */
					$('#fastlogin').click(function(){
						//uid
						chrome.tabs.create({
								'url': adminhost+"index.php?s=/login/fastlogin/uid/"+uid,'selected':true
							},function(tab2) {
	
							}
						);
					});
				}else{
					$("#fastlogindiv").hide();	
				}
				
				$(".logout-btn").click(function(){
					chrome.tabs.create({
							'url': 'https://login.taobao.com/member/logout.jhtml','selected':true
						},function(tab2) {
							 $.cookie(oc, null);
							 $.cookie("username", null);
							 $.cookie("password", null);
						}
					);
				});
			  }else{
				 $("#loading").html("加载失败");	  
			  }
			}
			xhr.send();
		}
	}
}	

function login(){
	/*
	chrome.tabs.create(
		{
			'url': 'http://www.cnblogs.com','selected':false
		},function(tab2) {
              console.log("OK");
		}
	);
	*/
	chrome.runtime.sendMessage({'cmd': "mycmd"},function(response){console.log(response);});
}

jQuery.cookie = function(name, value, options) { 
    if (typeof value != 'undefined') { // name and value given, set cookie 
        options = options || {}; 
        if (value === null) { 
            value = ''; 
            options.expires = -1; 
        } 
        var expires = ''; 
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 
            var date; 
            if (typeof options.expires == 'number') { 
                date = new Date(); 
				date.setTime(date.getTime() + (options.expires * 10 * 1000)); 
                //date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 
            } else { 
                date = options.expires; 
            } 
            expires = '; expires=' + date.toUTCString(); 
        } 
        var path = options.path ? '; path=' + (options.path) : ''; 
        var domain = options.domain ? '; domain=' + (options.domain) : ''; 
        var secure = options.secure ? '; secure' : ''; 
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
    } else { 
        var cookieValue = null; 
        if (document.cookie && document.cookie != '') { 
            var cookies = document.cookie.split(';'); 
            for (var i = 0; i < cookies.length; i++) { 
                var cookie = jQuery.trim(cookies[i]); 
                if (cookie.substring(0, name.length + 1) == (name + '=')) { 
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
                    break; 
                } 
            } 
        } 
        return cookieValue; 
    } 
};